<template>
    <div style="width:80%" v-if="model">
        <n-form
        ref="formRef"
        :model="model"
        :rules="rules"
        label-placement="left"
        label-width="180"
        size="small"
        >
        <template v-for="item in frontConfig" :key="item.FieldName">
            <n-form-item  v-if="item.Type !== 'subconfig'" :label="item.Label" :path="item.FieldName">
                <n-input-number v-if="item.Type === 'number'" :min="item.Min?item.Min:-Infinity" :max="item.Max?item.Max:Infinity" v-model:value="model[item.FieldName]" :placeholder="'please input '+item.FieldName" style="width:100%;" :show-button="false" />
                <n-switch v-else-if="item.Type === 'onoff'" v-model:value="model[item.FieldName]" />
                <n-select v-else-if="item.Type === 'select'" style="width:100px;" v-model:value="model[item.FieldName]" placeholder="Select" :options="options(item)" />
                <template v-else-if="item.Type === 'fileInput'">
                    <n-input v-model:value="model[item.FieldName]" :placeholder="'please input ' + item.Label" />
                    <n-button style="width:20%;" type="primary" size="small" @click="openFile(item)">OpenFile</n-button>
                </template>
                <template v-else-if="item.Type === 'clock'">
                    <ClockInput v-model:model-value="model[item.FieldName]" :field="item" />
                </template>
                <template v-else-if="item.Type === 'dirInput'">
                    <n-input v-model:value="model[item.FieldName]" :placeholder="'please input ' + item.Label" />
                    <n-button style="width:20%;" type="primary" size="small" @click="openDir(item)">OpenDir</n-button>
                </template>
                <template v-else-if="item.Type === 'dirArray'">
                    <MutiPathInput v-model:model-value="model[item.FieldName]" :field="item" />
                </template>
                <template v-else-if="item.Type === 'ledcolor'">
                    <LedColorInput v-model:model-value="model[item.FieldName]" />
                </template>
                <span v-if="item.Unit" class="unit">{{item.Unit}}</span>
            </n-form-item>
        </template>
        </n-form>
    </div>
</template>
<script setup lang="ts">
import { ref,onBeforeMount } from 'vue'
import { NForm, NFormItem, NSelect,NInputNumber,NSwitch,NButton,NInput } from 'naive-ui'
import type { FormRules } from 'naive-ui'
import { device,frontend } from '../../../wailsjs/go/models';
import { GetFile,GetDir } from '../../../wailsjs/go/main/App';
import { ledConfigStore } from '@/stores/ledconfig';
import type { DevSetting } from '@/scripts/types';
import MutiPathInput from './MutiPathInput.vue';
import LedColorInput from './LedColorInput.vue';
import ClockInput from './ClockInput.vue';


const formRef = ref();
const model = defineModel<DevSetting>("formValue");
const rules = ref<FormRules>({});

const props = defineProps({
    frontConfig: {
        type: Array as () => device.DevFrontendConfig[],
        required: true,
    }
})

const options = (field: device.DevFrontendConfig) => {
    return field.Options.map((item) => {
        return {
            label: item,
            value: item
        }
    })
}

async function openFile(field: device.DevFrontendConfig) {
    let opt = new frontend.OpenDialogOptions(`{"Title":"Open File","Filters":[{"DisplayName":"${field.Label}","Pattern":"${field.Filters}"}]}`)
    model.value![field.FieldName] = await GetFile(opt)
}

async function openDir(field: device.DevFrontendConfig) {
    let opt = new frontend.OpenDialogOptions(`{"Title":"Open Dir ${field.Label}"}`)
    model.value![field.FieldName] = await GetDir(opt)
}


onBeforeMount(() => {
    if (!model.value) {
        return;
    }
    props.frontConfig.forEach((item) => {
        rules.value[item.FieldName] = {
            required: item.Required,
            trigger: ['blur'],
            // message: 'Please input ' + item.Label,
            validator: () => {
                if (!item.Required) {
                    return true;
                }
                if (model.value == null 
                || (item.Required && !model.value[item.FieldName] && model.value[item.FieldName] !== false && model.value[item.FieldName] !== 0)
                ) {
                    console.log(item.FieldName,model.value![item.FieldName])
                    return Error('Please input ' + item.Label);
                }
                if (item.Type === 'number' && item.Min && model.value[item.FieldName] < item.Min) {
                    return Error('Please input ' + item.Label + ' greater than ' + item.Min);
                }
                if (item.Type === 'number' && item.Max && model.value[item.FieldName] > item.Max) {
                    return Error('Please input ' + item.Label + ' less than ' + item.Max);
                }
                return true;
            },
        }
        if(!(item.FieldName in model.value!)) {
            switch (item.Type) {
                case "onoff":
                    model.value![item.FieldName] = false
                    break;
                case "select":
                    model.value![item.FieldName] = item.Options[0]
                    break;
                case "clock":
                    model.value![item.FieldName] = 1
                    break;
                case "number":
                    model.value![item.FieldName] = 0
                    break;
                case "dirInput":
                    model.value![item.FieldName] = ""
                    break;
                case "dirArray":
                    model.value![item.FieldName] = []
                    break;
                default:
                    model.value![item.FieldName] = ""
            }
        }
    })
})

const verification = (): Promise<boolean> => {
    return new Promise((resolve,reject) => {
        formRef.value?.validate((errors:any) => {
            if (errors) {
                resolve(false)
            }else{
                resolve(true)
            }
        })
    })
}

defineExpose({
    verification
})

</script>
<style lang="scss" scoped>

</style>